//
//  XLNewHomeViewController.m
//  XiangLove
//
//  Created by feng song on 2018/1/18.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLNewHomeViewController.h"
 
#import "AoiroSoraLayout.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import "XLHTTPSessionManager.h"
#import "XLHTTPSessionManager+Camgirl.h"
#import "XLHTTPSessionManager+Analytics.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"
#import "XLTuijianBannnerListModel.h"
#import <ReactiveCocoa.h>
#import "XLTalkedPeopleModle.h"
#import "XLTalkedPeopleCell.h"
#import "MJRefresh.h"
#import "IMAChatViewController.h"
#import "XLPersonPageViewController.h"
#import "NewCamgirlModel.h"
#import "XLNewHomeCell.h"
#import "XLVideChatBtn.h"
#import "XLNewTopUpView.h"
#import "HomeCallModel.h"
#import "XLTopUpModel.h"
#import "CallMakeViewController.h"
#import "WeixinHelper.h"
#import "BMHAlertView.h"
#import <StoreKit/StoreKit.h>   //添加内购系统框架
#import "BMHStoreObserver.h"
#import <ImSDK/TIMFriendshipManager.h>
#import "IMAChatViewController.h"
#import "XLBeautyView.h"
#import "BMHPromptView.h"
#import "XLUsersReusableView.h"
#import "XLHosterReusableView.h"
#import "XLOrderViewController.h"
#import "XLMatchViewController.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLHTTPSessionManager+TaskLevel.h"
#import "XLNewOrderViewController.h"
#import "LKNotification.h"
#import "TopUpViewController.h"
#import <UIViewController+TopViewController.h>
#import "XLV2LoginViewController.h"
#import "XLAutoScrollView.h"
#import "XLWebViewController.h"
#import "XLAnchorCommitInforVC.h"
@interface XLNewHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,AoiroSoraLayoutDelegate,XLNewTopUpDelegate,LKNotificationDelegate>{
    XLAutoScrollView *lunbView;//轮播
}

@property (nonatomic,strong)UICollectionView    *collectionView;
@property (nonatomic,strong)NSMutableArray      *modelArray;
@property (nonatomic,copy  )NSString            *page;
@property (nonatomic,copy  )NSString            *firstUpdata;
@property (nonatomic,strong)XLUserInfoModel     *userInfoModel;
@property (nonatomic,strong)XLTalkedPeopleModle *talkedPeopleModle;
@property (nonatomic,strong)NewCamgirlModel     *currentCamgirlModel;
@property (nonatomic,assign)BOOL                shouldRefresh;
@property (nonatomic,strong)XLVideChatBtn       *videChatBtn;
@property (nonatomic,strong)XLNewTopUpView      *topUpview;
@property (nonatomic,strong)NSMutableArray      *topUpMoneyArr;
@property (nonatomic,strong)NSMutableArray      *topUpJDArr;
@property (nonatomic,copy  )NSString            *myMoney;
@property (nonatomic,strong)NSDictionary        *zfbDic;
@property (nonatomic,copy  )NSString            *actionType;
@property (nonatomic,copy  )NSString            *payorder;//支付宝订单号
@property (nonatomic,copy  )NSString            *productIds;
@property (nonatomic,strong)XLBeautyView        *beautyView;
@property (nonatomic,strong)BMHPromptView       *promptView;
@property (nonatomic,strong)XLHosterReusableView*hosterReuseableView;
@property (nonatomic,strong)UIView              *chatTopView;
@property (nonatomic,strong)UIView              *beautyTopView;
@property (nonatomic,strong)UILabel             *redPoint;
@property (nonatomic,strong)NSString            *onlinePeoples;
@property (nonatomic,strong)UILabel             *onlineNumsTitle;
@property (nonatomic,strong)UIImageView         *videochatTopImg;
@property (nonatomic,strong)NSMutableArray      *orderListAry;
@property (nonatomic,strong)NSMutableArray      *lunboArray;//轮播数组
@property (nonatomic,assign)NSInteger            orderInter;
@property (nonatomic,strong)NSString            *usersPicUrl;
@property (nonatomic,assign)BOOL                 isAppear;

@property (nonatomic,strong)NSString            *notiImgUrl;
@property (nonatomic,strong)NSString            *notiMatchID;
@property (nonatomic,strong)NSString            *notiNickName;
@property (nonatomic,strong)NSString            *Price;
@property (nonatomic,strong)NSString            *UserId;
@property (nonatomic,strong)NSDictionary        *dics;
@property (nonatomic,assign)BOOL                 isStateApper;

//记录滑动
@property (nonatomic, assign) float contentOffset;
@property (nonatomic, assign) float oldOffset;


@end

@implementation XLNewHomeViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self analyticsEvent11];
    self.isAppear = YES;
//    [self getLKNotificationManager].default_style = LK_NOTIFICATION_BAR_STYLE_DARK;
//    LKNotificationBar *notificationBar = [[self getLKNotificationManager] createWithTitle:self.notiNickName content:@"正在找人视频聊天" icon:self.notiImgUrl];
//    notificationBar.delegate = self;
//    [notificationBar showWithAnimated: YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _chatTopView.hidden = YES;
    _beautyTopView.hidden  = YES;
    self.isAppear = NO;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeType:) name:@"FirstViewDidScroollHost" object:nil];
    self.view.backgroundColor = XLBgColor;
    self.fd_prefersNavigationBarHidden = YES;
    self.isStateApper  = NO;
    self.zfbDic        = [NSDictionary   dictionary];
    self.topUpMoneyArr = [NSMutableArray array];
    self.topUpJDArr    = [NSMutableArray array];
    self.orderListAry  = [NSMutableArray array];
    self.lunboArray = [NSMutableArray array];
    [self addCollectionView];
    [self addObserver];
//    [self refreshUserInfo];
    if (@available(iOS 11.0, *)) {
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OrderNotifyExtNotification:) name:@"OrderNotifyExt" object:nil];
    [self downloadBannerList];
    self.page = @"1";
    [self requrstTalkedPeoplePage:self.page];
    [self MakeData];
}

#pragma mark -抢单通知
- (void)OrderNotifyExtNotification:(NSNotification *)notification {
    TIMMessage *msg = notification.object;
    TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
    NSLog(@"dic==%@",dic);
    self.dics = dic;
    self.notiImgUrl     = [NSString stringWithFormat:@"%@",dic[@"ImgUrl"]];
    self.notiMatchID    = [NSString stringWithFormat:@"%@",dic[@"MatchId"]];
    self.notiNickName   = [NSString stringWithFormat:@"%@",dic[@"NickName"]];
    self.Price          = [NSString stringWithFormat:@"%@",dic[@"Price"]];
    self.UserId         = [NSString stringWithFormat:@"%@",dic[@"UserId"]];
    

    if ([[UIViewController topViewController] isKindOfClass:NSClassFromString(@"XLFoundViewController")] ||
        [[UIViewController topViewController] isKindOfClass:NSClassFromString(@"ConversationListViewController")] ||
        [[UIViewController topViewController] isKindOfClass:NSClassFromString(@"XLMineViewController")] ) {
         if (![[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {
            [self getLKNotificationManager].default_style = LK_NOTIFICATION_BAR_STYLE_DARK;
            LKNotificationBar *notificationBar = [[self getLKNotificationManager] createWithTitle:self.notiNickName content:@"正在找人视频聊天" icon:self.notiImgUrl];
            notificationBar.delegate = self;
            [notificationBar showWithAnimated: YES];
         }
        
    }
    
   
}

-(void)onNavigationBarTouchUpInside:(LKNotificationBar *)navigationBar
{
    [navigationBar hideWithAnimated:YES];
    if ([self checkCameraAuthorization]) {
        [self grabOrder:self.dics];
    }
    
    
}

- (void)grabOrder:(NSDictionary *)dic {
    
    [[[XLHTTPSessionManager sharedManager] grabOrderWithUserId:dic[@"UserId"] anchorId:[[XLAccountManager shareInstance] model].Id matchId:dic[@"MatchId"]] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        NSInteger result = [x[@"result"] integerValue];
        if (result == 0) { //抢单成功，发送自定义消息
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
                [self sendGrabOrderCustomMessageWithOrderNum:dic[@"MatchId"] orderUserId:dic[@"UserId"] orderNickName:[[XLAccountManager shareInstance] model].NickName orderHeadImg:[[XLAccountManager shareInstance] model].HeadImg];
            } else {
                @weakify(self);
                [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:dic[@"UserId"] userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
                    @strongify(self);
                    HomeCallModel *model = x;
                    NSString *callID =  F(@"%@", model.CallId);
                    CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
                    make.IsOneTimeCall = model.IsOneTimeCall;
                    make.UserFreeSecond = model.UserCardSecond;
                    make.peerId = [NSString stringWithFormat:@"%@",dic[@"UserId"]];
                    make.headStr = dic[@"ImgUrl"];
                    make.nickNameStr = dic[@"NickName"];
                    make.detailStr = [NSString stringWithFormat:@"%@ %@",dic[@""],dic[@""]];
                    make.addressStr = dic[@""];
                    make.ageStr = [dic[@""] integerValue];
                    make.jobStr = dic[@""];
                    make.ismic = YES;
                    make.iscinema = YES;
                    make.callid = callID;
                    make.videoid = [NSString stringWithFormat:@"%@",callID];
                    make.moneyStr = @"20";
                    make.gradeStr = [NSString stringWithFormat:@"%@",dic[@""]];
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:make animated:YES completion:nil];
                    
                } error:^(NSError *error) {
                    @strongify(self);
                    NSLog(@"%@", error);
                    if (error.code == 6) {  //余额不足
                        //[HelpTool startTipViewWithText:@"你的账号余额不足，请充值！" duration:2.0f type:kTipViewTypeNone];
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"你的余额不足,是否前往充值?" preferredStyle: UIAlertControllerStyleAlert];
                        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        }]];
                        [alert addAction:[UIAlertAction actionWithTitle:@"充值" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            TopUpViewController *topVC = [[TopUpViewController alloc] initWithBeautyid:[[NSUserDefaults standardUserDefaults] objectForKey:UserID]];
                            topVC.In_purchase = isIn_purchase;
                            [self.navigationController pushViewController:topVC animated:YES];
                        }]];
                        [self.navigationController presentViewController:alert animated:YES completion:nil];
                        
                    } else if (error.code == -4) {  //被拉入黑名单
                        [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
                    } else if (error.code == -3) {  //对方已屏蔽视聊
                        [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
                        IMAMsg *msgs = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
                        IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:[NSString stringWithFormat:@"%@",dic[@"UserId"]]];
                        [conversation sendMessage:msgs completion:^(NSArray *imamsgList, BOOL succ, int code) {
                        }];
                    } else {  //创建失败
                        [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                    }
                }];
            }
        } else if (result == -10001 || result == -10003) {
            NSString *str;
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
                str = @"该用户已经被其他美女抢走了，看看其他用户吧";
            } else {
                str = @"该美女已经被其他用户抢走了，看看其他美女吧";
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你手慢了" message:str preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:NULL];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:str attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            [alert setValue:atr forKey:@"attributedMessage"];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:NULL];
        } else if (result == -10002) {
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
                [MBProgressHUD showContent:@"该美女已经取消了通话，看看其他美女吧" toView:self.view];
                return ;
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"用户已取消通话" message:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" preferredStyle:UIAlertControllerStyleAlert];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            
            [alert setValue:atr forKey:@"attributedMessage"];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:NULL];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"邀请他" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:F(@"%@", dic[@"UserId"])];
                NSDictionary * xmlDic = @{
                                          @"action": @8,
                                          @"imageUrl": [[XLAccountManager shareInstance] model].HeadImg ?: @"",
                                          };
                IMAMsg *msg = [IMAMsg shareToGroupMsgWithCustomDic:xmlDic];
                [conversation sendMessage:msg completion:^(NSArray *imamsglist, BOOL succ, int code) {
                    
                }];
            }];
            [alert addAction:action1];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:NULL];
        } else {
            [MBProgressHUD showContent:x[@"msg"] toView:self.view];
        }
        
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:@"抢单失败" toView:self.view];
    }];
}

- (void)sendGrabOrderCustomMessageWithOrderNum:(NSString *)orderNum orderUserId:(NSString *)orderUserId orderNickName:(NSString *)orderNickName orderHeadImg:(NSString *)orderHeadImg {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [self sendCustomMessageWithOrderNum:orderNum userId:orderUserId eventId:3 nickName:orderNickName headImg:orderHeadImg groupId:nil completion:NULL];
    }
}

- (void)sendCustomMessageWithOrderNum:(NSString *)orderNum userId:(NSString *)userId eventId:(NSInteger)eventId nickName:(NSString *)nickName headImg:(NSString *)headImg groupId:(NSString *)groupId completion:(void (^)(void))completion {
    TIMMessage *msg = [[TIMMessage alloc] init];
    TIMOfflinePushInfo *info = [[TIMOfflinePushInfo alloc] init];
    info.pushFlag = TIM_OFFLINE_PUSH_NO_PUSH;
    [msg setOfflinePushInfo:info];
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    NSDictionary *dic;
    if (groupId) {
        dic = @{
                @"groupId"  : groupId ?: @"",
                @"orderNum" : orderNum ?: @"",
                @"hostUserId" : userId,
                @"event" : @(eventId),
                @"name" : nickName,
                @"headimg" : headImg
                };
    } else {
        dic = @{
                @"oppositeUserId" : userId ?: @"",
                @"orderNum": orderNum ?: @"",
                @"name" : nickName ?: @"",
                @"headimg" : headImg ?: @"",
                @"leval" : @"1",
                @"levalIcon" : @"",
                @"address" : @"",
                @"age" : @"",
                @"job" : @""
                };
    }
    
    elem.data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    if (groupId) {
        elem.desc = @"CallOrderExt";
        elem.ext = @"CallOrderExt";
    } else {
        elem.desc = @"QiangDanNotification";
        elem.ext = @"QiangDanNotification";
    }
    
    [msg addElem:elem];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:groupId ? TIM_GROUP : TIM_C2C receiver:groupId?: userId];
    [con sendOnlineMessage:msg succ:^{
        if (completion) {
            completion();
        }
    } fail:^(int code, NSString *msg) {
        [MBProgressHUD showContent:msg toView:self.view];
        if (completion) {
            completion();
        }
    }];
}



-(void)MakeData
{
    [BMHHTTPSession GETBMHVideo:@"/api/v1/VideoChatInfo/GetRechareInfo" paraments:@{@"type":@"1"} success:^(id  _Nullable JSON) {
        NSLog(@"接口返回充值金额:%@",JSON);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }else{
            [self getTopupList:JSON[@"data"]];
        }
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@", error);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }else{
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"30",@"50",@"100",@"500", nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"300",@"500",@"1000",@"5000",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }
    }];
}

-(void)reshOnlinePeoplesData
{
    [[[XLHTTPSessionManager sharedManager] getTalkedOnlinePeoplesWithAppID] subscribeNext:^(id x) {
        NSLog(@"接口人数");
        NSString * successState = [NSString stringWithFormat:@"%@",x[@"success"]];
        if ([successState isEqualToString:@"0"]) {
            self.onlinePeoples = [NSString stringWithFormat:@"%@",x[@"data"][@"online"]];
            self.onlineNumsTitle.text = [NSString stringWithFormat:@"%@人在线",self.onlinePeoples];
            [self.collectionView reloadData];
        }else{
            
        }
    } error:^(NSError *error) {
        
    }];
    
    [[[XLHTTPSessionManager sharedManager] getMatchPicData] subscribeNext:^(id x) {
        NSLog(@"首页展示图片");
        self.usersPicUrl = [NSString stringWithFormat:@"%@",x[@"info"]];
        [self.collectionView reloadData];
    } error:^(NSError *error) {
        
    }];
    
    [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSLog(@"订单列表数据==%@",x);
        self.orderListAry = x;
        if (self.orderListAry.count > 0 || self.orderListAry.count == 0) {
            self.orderInter = self.orderListAry.count;
            [self updateCellOnline];
        }
        [self.collectionView reloadData];
    } error:^(NSError *error) {
        
    }];
}




-(void)getTopupList:(NSMutableArray *)arr
{
    for (int i = 0; i < arr.count; i++) {
        
        XLTopUpModel * topupMd = [XLTopUpModel modelWithDictionary:arr[i]];
        [self.topUpMoneyArr addObject:topupMd.money];
        [self.topUpJDArr    addObject:topupMd.jindou];
        if (i == 0) {
            self.myMoney = topupMd.money;
        }
    }
    
}

- (void)addObserver {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"OrderRefresh" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        if (self.isAppear) {
            //[self reshOnlinePeoplesData];
        }
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"zhifusuccess" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self analyticsEvent10];
        [self refreshUserInfo];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:BMHRefreshUserInfo object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self refreshUserInfo];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"repeatSelectRecommand" object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self.collectionView.mj_header beginRefreshing];
    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self performSelector:@selector(refresh) withObject:nil afterDelay:60];
        UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] subscribeNext:^(id x) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refresh) object:nil];
        if (self.shouldRefresh) {
            [self handelGCHeaderTableView];
            self.shouldRefresh = NO;
        }
    }];
}

- (void)refresh {
    if (self.navigationController.topViewController == self) {
        self.shouldRefresh = YES;
    }
}

- (void)refreshUserInfo {
    [[[XLHTTPSessionManager sharedManager] getUserInfoWithUserId:[[XLAccountManager shareInstance] model].Id secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
        self.userInfoModel = x;
        [UserDefaults setObject:self.userInfoModel.Id forKey:UserID];
        [UserDefaults setObject:self.userInfoModel.HeadImg forKey:UserHead];
        [UserDefaults setObject:self.userInfoModel.NickName forKey:UserNick];
        self.userInfoModel.SecretKey = [[XLAccountManager shareInstance] model].SecretKey;
        [[XLAccountManager shareInstance] updateUserInfo:self.userInfoModel];
    } error:^(NSError *error) {
        
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

#pragma mark --初始化CollectionView
-(void)addCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 6;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
//    flowLayout.headerReferenceSize = CGSizeMake(XQScreenW, SCREEN_WIDTH/3);
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, XQScreenW, XQScreenH - 49) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = kWhiteColor;
    [_collectionView registerClass:[XLNewHomeCell class] forCellWithReuseIdentifier:NSStringFromClass([XLNewHomeCell class])];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderHost"];
    //[_collectionView registerClass:[XLUsersReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    header.stateLabel.hidden = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    _collectionView.mj_header = header;
    [self.view addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 49, 0));
    }];
    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[(id)RGBA(0, 0, 0, 0).CGColor, (id)RGBA(0, 0, 0, 0.5).CGColor];
//    gradientLayer.locations = @[@(0.5)];
//    gradientLayer.startPoint = CGPointMake(0.5, 1);
//    gradientLayer.endPoint = CGPointMake(0.5, 0);
//    gradientLayer.frame = CGRectMake(0, 0, ScreenWidth, 40);
//    [self.view.layer addSublayer:gradientLayer];
    
}
- (void)downloadBannerList{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"Api/v2/HomePage/GetBanners" parameters:@{@"type":@"0"} resultClass:[XLTuijianBannnerListModel class]]subscribeNext:^(id x) {
        if ([x isKindOfClass:[NSNull class]]) {
            return;
        }
        self.lunboArray =(NSMutableArray *)x;
        if (_lunboArray.count > 0) {
            if (lunbView == nil) {
                lunbView = [[XLAutoScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/3)];
                [lunbView changeShowDict:_lunboArray
                               andBlocks:^(NSInteger shopTags) {
                                   if ( shopTags < _lunboArray.count ) {
                                       XLTuijianBannnerListModel *topM = _lunboArray[shopTags];
                                       [self WanNengPush:topM.Url];
                                   }
                               }];
            }
        }
    } error:^(NSError *error) {
        
    }];
}

/**
 *  跳转界面
 */
- (void)WanNengPush:(NSString *)VCName //后台给的vc名字
{
    if ([VCName rangeOfString:@"https://"].location != NSNotFound || [VCName rangeOfString:@"http://"].location != NSNotFound){  //网页链接
        XLWebViewController *vc = [[XLWebViewController alloc] init];
        vc.url = VCName;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSString *class = @"";//XLMyLevelViewController //XLTaskViewController
        if ([VCName rangeOfString:@"activity://"].location != NSNotFound){
            class = [[VCName componentsSeparatedByString:@"//"] lastObject];
        }
        const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
        // 从一个字串返回一个类
        Class newClass = objc_getClass(className);
        if (!newClass)
        {   // 创建一个类
            Class superClass = [NSObject class];
            newClass = objc_allocateClassPair(superClass, className, 0);
            // 注册你创建的这个类
            objc_registerClassPair(newClass);
        }
        // 创建对象
        id instance = [[newClass alloc] init];
        NSDictionary *propertys = @{@"":@""};
        [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            // 检测这个对象是否存在该属性
            if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
                // 利用kvc赋值
                [instance setValue:obj forKey:key];
                [self.navigationController pushViewController:instance animated:YES];
                
            }else{
                [MBProgressHUD showContent:@"敬请期待"];
            }
            
        }];
    }
}

/**
 *  检测对象是否存在该属性
 */
- (BOOL)checkIsExistPropertyWithInstance:(id)instance verifyPropertyName:(NSString *)verifyPropertyName
{
    unsigned int outCount, i;
    
    // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList([instance class], &outCount);
    
    for (i = 0; i < outCount; i++) {
        objc_property_t property =properties[i];
        //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        // 判断该属性是否存在
        if ([propertyName isEqualToString:verifyPropertyName]) {
            free(properties);
            return YES;
        }
    }
    free(properties);
    return NO;
}
- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)requrstTalkedPeoplePage:(NSString *)page
{
//    self.userInfoModel = [[XLAccountManager shareInstance] model];
    NSDictionary *dic = @{@"pageIndex":_page,
                          @"pageSize":@"16",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"type":@"0"
                          };
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/api/v2/HomePage/GetHomePageList" parameters:dic resultClass:[NewCamgirlModel class]] subscribeNext:^(id x) {
        NSLog(@"美女列表==%@",x);
        [MBProgressHUD hideHUDForView:self.view];
        self.collectionView.hidden = NO;
        [_promptView removeFromSuperview];
        _promptView = nil;
        NSArray * listAry = x;
        if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
            [self getJsonArray:listAry];
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
        }else{
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        if (self.modelArray.count == 0) {
            self.promptView.hidden = NO;
//            self.collectionView.hidden = YES;
        }
        
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"1"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.collectionView reloadData];
}

#pragma mark -XLNewTopUpDelegate
-(void)XLSelectedJD:(UIButton *)selectedBtn
{
    
    self.myMoney = [self.topUpMoneyArr objectAtIndex:selectedBtn.tag];
    BMHLog(@"选择了%@",self.myMoney);
}

-(void)XLNewtestTopup
{
    self.myMoney = @"1";
}

#pragma mark - 微信充值
-(void)XLNewWXZHIFU:(UIButton *)wxBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
        
    } else {
        [self analyticsEvent9];
        [[WeixinHelper sharedWeixinHelper] getUrlWithWXMoney:self.myMoney Months:@"0" TranstypeId:@"1" RemarksInfo:RemarksRose KKOrder:@"" kkUserid:@""];
        
        self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
    }
}
- (void)topupViewDidDisAppear {
    [self analyticsEvent8];
}

#pragma mark - 支付宝支付
-(void)XLNewZFBZHIFU:(UIButton *)zfbBtn;
{
    
//    if (!([self.myMoney integerValue] > 0)) {
//        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
//    } else {
//        [self analyticsEvent7];
//        self.actionType = @"1";
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        [[[XLHTTPSessionManager sharedManager] getZFBPlayOrder:self.userInfoModel.Id giftId:@"1" TransType:self.actionType payType:@"4" FeeType:@"" Money:self.myMoney PrivateInfo:zhf_PrivateKey Remarks:RemarksRose Months:@"0" secretKey:self.userInfoModel.SecretKey] subscribeNext:^(id x) {
//            BMHLog(@"===支付宝创建订单===%@",x);
//            NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
//            self.payorder      = [NSString stringWithFormat:@"%@",x[@"data"]];
//            if ([success isEqualToString:@"0"]) {
//                NSString *money = [NSString stringWithFormat:@"%.2f", [self.myMoney floatValue]];
//                [ZhifuHelp InPutzhifubaoWithDingdan:self.payorder Money:money subjesct:RemarksRose body:RemarksRose successBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                    
//                } failBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                }];
//                
//                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
//                
//            } else {
//                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
//                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
//            }
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            
//            
//        } error:^(NSError *error) {
//            NSLog(@"错误:%@",error);
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            [MBProgressHUD showContent:@"加载失败,请重试!" toView:self.view];
//            
//        }];
//    }
}

#pragma mark - AppstorePay(内购)
-(void)xlAppstorePay:(UIButton *)payBtn
{
    [self hadenlTopUpIn_purchase:payBtn];
}

#pragma mark - AppStore内购支付订单
- (void)hadenlTopUpIn_purchase:(UIButton *)sender {
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        
        self.actionType = @"1";
        [MBProgressHUD showMessage:nil];
        NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *actionType = self.actionType;
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        self.zfbDic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"Type",uid,@"Userid",@"1",@"Giftid",self.actionType,@"Transtype",@"6",@"Paytype",@"",@"Feetype",self.myMoney,@"Money",zhf_PrivateKey,@"Privateinfo",RemarksRose,@"Remarks",@"0",@"Months",locationString,@"Timestamp",nat,@"Appsign",kAppTypeOrId,@"appid",KAPPFr,@"qudao",nil];
        
        [BMHHTTPSession GET:@"/MobileInterface/Pay/AliPay.ashx" paraments:self.zfbDic success:^(id  _Nullable JSON) {
            NSLog(@"===苹果内购创建订单===%@",JSON);
            NSString *errcode = JSON[@"result"][@"errcode"];
            self.payorder = JSON[@"result"][@"OrderNo"];
            if ([errcode isEqualToString:@"0"]) {
                self.productIds= [NSString stringWithFormat:@"XLVideoChat%@",self.myMoney];
                if([SKPaymentQueue canMakePayments])
                {
                    //buy AppStore Products
                    [[BMHStoreObserver sharedInstance] buy:self.productIds withPayMonyNum:self.myMoney andPayOrder:self.payorder];
                    self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                    
                }else
                {
                    BMHLog(@"不允许程序内付费");
                }
                
            } else {
                
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            [MBProgressHUD hideHUD];
        } failure:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
        }];
    }
}

#pragma mark - getter
- (BMHPromptView *)promptView {
    if (_promptView == nil) {
        _promptView = [[BMHPromptView alloc] initWithImage:[UIImage imageNamed:@"common_img_wifi_d"]];
        [self.view addSubview:_promptView];
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(200, 215));
            make.center.equalTo(self.view);
        }];
        @weakify(self);
        _promptView.touchBlock = ^{
            @strongify(self);
            [self handelGCHeaderTableView];
        };
    }
    return _promptView;
}

#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.firstUpdata = @"1";
    self.page = @"1";
    [self requrstTalkedPeoplePage:self.page];
    //[self reshOnlinePeoplesData];
    
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.firstUpdata = @"1";
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage:self.page];
}

#pragma mark - CollectionDelegate
#pragma mark -- 返回每个item的高度
//每个item的纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 8;
}

//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(0, 10, 8, 10);//分别为上、左、下、右
//}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((XQScreenW-27)/2,((XQScreenW-25)/2)*200/174);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (_lunboArray.count == 0) {
        return CGSizeMake(XQScreenW,0);
    }
//    return CGSizeMake(XQScreenW,0);
    return CGSizeMake(XQScreenW,(SCREEN_WIDTH-20) * 19 /71 + 18);
}

#pragma mark -- collectionView 的分组个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


#pragma mark -- item 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
    
}

#pragma mark -- cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewCamgirlModel * model = self.modelArray[indexPath.row];
    XLNewHomeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([XLNewHomeCell class]) forIndexPath:indexPath];
    cell.dataModels = model;
    cell.videChatBtn.hostIndex = indexPath.row;
    [cell.videChatBtn addTarget:self action:@selector(videoChat:) forControlEvents:UIControlEventTouchUpInside];
    cell.backgroundColor = XLThemeColor;
    return cell;
}

#pragma mark -- 选中某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self analyticsEvent12];
    
    NewCamgirlModel *model = self.modelArray[indexPath.row];
    //跳转私聊界面
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model.UserId)] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
//                    chat.isAnchor = model[@"IsAnchor"];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark -VideoChatEvent
-(void)videoChat:(XLVideChatBtn *)sender
{
    XLVideChatBtn * videBtn = (XLVideChatBtn*)sender;
    self.videChatBtn.enabled = NO;
    [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:0.5f];
    NewCamgirlModel *model = self.modelArray[videBtn.hostIndex];
    if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue] == YES) {
        
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
    } else {
        
        if ([model.OnlineStatus  isEqualToString:@"1"] || [model.OnlineStatus isEqualToString:@"3"]) {
            [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
                for (TIMUserProfile *pro in friends)
                {
                    IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                        [self.navigationController pushViewController:chat animated:YES ];
                    });
                }
            } fail:^(int code, NSString *msg) {
                DebugLog(@"vvvFailddd: %d->%@", code, msg);
            }];
        }else{
            if ([self checkCameraAuthorization])
            {
                if ([[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] > 0) {
                    [self analyticsEvent13];
                    [self videoChatWithCamgirl:self.modelArray[videBtn.hostIndex]];
                    
                } else {
                    [self analyticsEvent5];
                    self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
                    self.topUpview.delegate = self;
                    [self.view addSubview:self.topUpview];
                }
                
            }
        }
       
    }
}
-(void)changeButtonStatus{
    self.videChatBtn.enabled =YES;
}


- (void)videoChatWithCamgirl:(NewCamgirlModel *)model {
    BMHLog(@"和%@去视频聊天", model.NickName);
    if ([model.UserId isEqualToString:[[XLAccountManager shareInstance] model].Id]) {
        [MBProgressHUD showContent:@"不能自嗨哟！" toView:self.view];
        return;
    }
    NSString * useridStr = model.UserId;
    NSDate * senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    //令牌
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = kBMHRequestTimeFormat;
    NSString *sTime = [fmt stringFromDate:now];
    NSString *objID = @"0";
    NSString *publicKey = @"BMH2014YDYWB";
    NSString *nat = [NSString stringWithFormat:@"%@%@0%@%@",objID,useridStr, publicKey, sTime];
    nat = [nat md5Encrypt];
    
    NSDictionary * UserInfoDic = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"type",useridStr,@"userId",locationString,@"Timestamp",nat,@"appsign",nil];
    [MBProgressHUD showMessage:@"" toView:self.view];
    [BMHHTTPSession GET:@"/MobileInterface/PayVoiceVideo/PayVoiceVideo.ashx" paraments:UserInfoDic success:^(id  _Nullable JSON) {
        NSLog(@"=====dd个人资料json====%@",JSON);
        NSString  *status  =  JSON[@"result"][@"errcode"];
        [MBProgressHUD hideHUDForView:self.view];
        if ([F(@"%@", status) isEqualToString:@"803"]) {
            [MBProgressHUD showContent:@"对方取消了视频通话功能" toView:self.view];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:model.UserId];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
                
            }];
        }else{
            HomeCallModel *model = [[HomeCallModel alloc] initWithDict:JSON[@"result"][@"data"]];
            if ([self checkCameraAuthorization]) {
                [self chatWithModel:model];
            }
        }
    } failure:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

#pragma mark - CallEvent
- (void)chatWithModel:(HomeCallModel *)model {
    
    [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:model.UserId userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSString * callID =  F(@"%@", x[@"CallId"]);
        CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
        make.IsOneTimeCall = [x[@"IsOneTimeCall"] boolValue];
        make.UserFreeSecond = [x[@"UserCardSecond"] intValue];
//        make.UserFreeSecond = model.UserCardSecond;
        make.peerId = [NSString stringWithFormat:@"%@",model.UserId];
        make.headStr = model.HeadImg;
        make.nickNameStr = model.NickName;
        make.detailStr = [NSString stringWithFormat:@"%@ %@",model.HostCity,model.job];
        make.addressStr = model.HostCity;
        make.ageStr = model.Age;
        make.jobStr = model.job;
        make.ismic = YES;
        make.iscinema = YES;
        make.callid = callID;
        make.videoid = [NSString stringWithFormat:@"%@",callID];
        make.moneyStr = @"20";
        make.gradeStr = [NSString stringWithFormat:@"%@",model.BGradeIcon];
        
        [self presentViewController:make animated:YES completion:nil];
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        if (error.code == 6) {  //余额不足
            [self analyticsEvent5];
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
        } else if (error.code == -4) {  //被拉入黑名单
            [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
        } else if (error.code == -3) {  //对方已屏蔽视聊
            [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
            IMAMsg *msg = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
            IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:[NSString stringWithFormat:@"%@",model.UserId]];
            [conversation sendMessage:msg completion:^(NSArray *imamsgList, BOOL succ, int code) {
            }];
        } else {  //创建失败
            [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
        }
    }];
}


- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }
    
    if (!isAvalible) {
        [self analyticsEvent14];
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [self presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark - CollectionHead
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader) {
          if (reusableview == nil) {
              reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderHost" forIndexPath:indexPath];
           }
    }
    if (_lunboArray.count > 0) {
        [reusableview addSubview:lunbView];
    }
    
    return reusableview;
}

-(void)hostTopTapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tapTop =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(tapTapAction:)];
    [view addGestureRecognizer:tapTop];
}
-(void)hostTapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(hostTapAction:)];
    [view addGestureRecognizer:tap];
}

#pragma mark -
#pragma mark - 头部事件
-(void)tapTapAction:(UITapGestureRecognizer *)Toptap
{
    if ([self checkCameraAuthorization]) {
        [self analyticsEvent17];
        [self analyticsEvent18];
        XLOrderViewController *vc = [[XLOrderViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark -
#pragma mark -主播-抢单大厅
-(void)hostTapAction:(UITapGestureRecognizer *)tap
{
    //主播-抢单大厅
    NSLog(@"主播-抢单大厅");
    if ([self checkCameraAuthorization]) {
        [self analyticsEvent17];
        [self analyticsEvent18];
        XLNewOrderViewController *vc = [[XLNewOrderViewController alloc] init];
        vc.view.backgroundColor=[UIColor colorWithWhite:0 alpha:0.77];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [self presentViewController:vc animated:YES completion:^(void){
            vc.view.superview.backgroundColor = [UIColor clearColor];
        }];
       }
}
//创建手势
-(void)tapGestureRecognizer:(UIView *)view
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self     action:@selector(tapAction:)];
    [view addGestureRecognizer:tap];
}
#pragma mark -
#pragma mark -用户-匹配美女
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    //用户-进入匹配美女
    NSLog(@"用户-进入匹配美女");
    
    if ([[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] >= 50) {
        
        if ([self checkCameraAuthorization]) {
            [self analyticsEvent15];
            [self analyticsEvent16];
            XLMatchViewController *vc = [[XLMatchViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else {
        [self analyticsEvent5];
        if (self.topUpMoneyArr.count > 0) {
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
        }
        
    }
}

#pragma mark ----判断tableview上滑还是下滑
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.contentOffset = scrollView.contentOffset.y;
}


//记录滑动结束时候的offset
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.oldOffset = scrollView.contentOffset.y;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    CGFloat newOffsetY = scrollView.contentOffset.y;
    if (newOffsetY > self.oldOffset && self.oldOffset > self.contentOffset){//上滑
        //写上滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(NO);
        }
    }else if(newOffsetY < self.oldOffset && self.oldOffset < self.contentOffset){//下滑
        //写下滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(YES);
        }
    }
    self.oldOffset = scrollView.contentOffset.y;
    if (scrollView.contentOffset.y>=200) {
        if ([self.userInfoModel.IsAnchor isEqualToString:@"0"])
        {
            _chatTopView.hidden   = NO;
            
            
        }else{
            _beautyTopView.hidden = NO;
        }
        
    }else{
        _chatTopView.hidden   = YES;
        _beautyTopView.hidden = YES;
    }
}



#pragma mark -
#pragma mark - 开始抢单
-(void)StartGrabSingle
{
    _beautyTopView = [[UIView alloc] init];
    _beautyTopView.hidden = YES;
    [self.view addSubview:_beautyTopView];
    [self hostTapGestureRecognizer:_beautyTopView];
    [_beautyTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.bottom.equalTo(self.view.mas_bottom).offset(-20);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    _videochatTopImg = [[UIImageView alloc] init];
    _videochatTopImg.image = [UIImage imageNamed:@"home_but_qiang2_n"];
    [_beautyTopView addSubview:_videochatTopImg];
    [_videochatTopImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_beautyTopView);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    _redPoint = [[UILabel alloc] init];
    _redPoint.textColor = kWhiteColor;
    _redPoint.font = kSetFont(10);
    _redPoint.layer.masksToBounds = YES;
    _redPoint.layer.cornerRadius  = 8;
    _redPoint.backgroundColor = RGBA(248, 75, 90, 1);
    _redPoint.textAlignment = NSTextAlignmentCenter;
    [_videochatTopImg addSubview:_redPoint];
}
- (void)updateCellOnline
{
    NSInteger readCount = self.orderInter;
    if ( readCount <= 9 &&  readCount > 0)
    {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(20, 16));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
    }else if (readCount >= 10) {
        _redPoint.hidden = NO;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 20));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
    }else {
        _redPoint.hidden = YES;
        [_redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(0, 0));
            make.center.equalTo(_videochatTopImg).centerOffset(CGPointMake(18, -9));
        }];
    }
    [_redPoint setText:readCount > 99 ? @"99+" : [NSString stringWithFormat:@"%ld",readCount]];
}

#pragma mark - analyticsEvent
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"userid"];
    }
    if (self.currentCamgirlModel.UserId) {
        [attributes setObject:self.currentCamgirlModel.UserId ?: @"" forKey:@"camgirlid"];
    }
    return attributes.copy;
}

- (void)analyticsEvent1 {//进入老用户首页
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_oldindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_oldindex" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent2 {//视频聊天按钮
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_videochat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_click_videochat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent3 {//消息
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_message" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_click_message" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent4 {//我的
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_headimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_click_my" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent5 {//弹出"充值界面"
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_popup_charge" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_popup_charge" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent6 {//向上滑动
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_up" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_slide_up" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent7 {//向下滑动
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_slide_down" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_slide_down" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent8 {//点击“充值界面”弹层中的取消
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_chargecancel" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_click_chargecancel" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent9 {//点击“充值界面”中去充值按钮
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_click_chargego" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_click_chargego" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

- (void)analyticsEvent10 {//充值返回统计
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"old_charge_back" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"old_charge_back" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}


-(void)analyticsEvent11{//面进入的统计代码
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_imgindex" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_imgindex" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}
-(void)analyticsEvent12{//点用户图片
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_clickimg" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

-(void)analyticsEvent13{//点视频通话
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickchat" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_clickchat" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}
-(void)analyticsEvent14{//有钱用户准备进随机匹配
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_refusepurview" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_refusepurview" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

-(void)analyticsEvent15{//点顶部大图
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_userclicktopimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_userclicktopimg" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

-(void)analyticsEvent16{//点浮层进入呼叫等待
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_userclickpopimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_userclickpopimg" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

-(void)analyticsEvent17{//主播点顶部大图
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_anchorclicktopimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_anchorclicktopimg" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

-(void)analyticsEvent18{//主播点浮层进入呼叫等待
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_anchorclickpopimg" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_imgindex" action:@"xl_anchorclickpopimg" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}


@end
